// curriculum//pages/purchase/index.js
const api = require('../../../utils/api').apis;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    escis: false,
    buyis: false,
    currName: '',
    currimg: '',
    money: 0,
    price: 0,
    integralis: false,
    weixin: true,
    showModalStatus: '',
    animationData: '',
    cope: 0,
    type: '',
    signUpNowis: false,
    paid: 0,
    coupon: 0,
    dedu: 0,
    recommend: true,
    unload: false,
    discountId: 0,
    res: {},
    classification: '',
    name: '',
    remark: '',
    discountis: true,
    purchase:0,
    dingis:true,
    corderNo:'',
    score:'',
    couponMoney:'',
    payMoney:'',
    isOriginalPrice:'',
  },
  // 使用订单号支付
  confirmPayCorderNo(){
    api.orderPayByOrderJsAPIApplet({
      orderNumber:this.data.corderNo
    }).then(res=>{
      console.log(res)
      this.requestPayment(res.data)
    })
  },
  // 支付 获取订单号
  confirmPay() {
      let that = this;
      let name = this.data.name
      let remark = this.data.remark
      console.log(this.data.id)
      let courseClassification = this.data.classification
      let couponsId = this.data.discountId ? this.data.discountId : null
      if(this.data.coupon == 0){
        couponsId = null
      }
      let isBalance = this.data.integralis ? 'no' : 'yes'
      if(this.data.paid >0){
        // wx.showLoading({})
        if(!this.data.weixin){
          console.log('未勾选')
          wx.showToast({
            icon:'none',
            title:'请选择支付方式'
          })
        } else{
          if(this.data.purchase == 0){
            this.setData({
              purchase:1
            })
            api.getprepayment({
              isOriginalPrice:this.data.isOriginalPrice,
              // 课程类型（线下：offline，线上：online，直播：live）
              courseClassification: courseClassification,
              // 课程id
              courseId: this.data.id,
              // 优惠卷id (不传为null，则未使用优惠卷)
              couponsId: couponsId,
              // 是否使用余额， yes使用，no不使用
              isBalance: isBalance,
              // 上级分销用户Id(非必传）
              invitationUser: null,
              name: name,
              remark: remark,
            }).then(res => {
              console.log(res)
              wx.hideLoading()
              api.orderPayByOrderJsAPIApplet({
                orderNumber:res.data
              }).then(res=>{
                console.log(res)
                this.requestPayment(res.data)
              })
        
            })
          } else{
            console.log('多次点击')
          }
        }
      } else{
        // wx.showLoading({})
        api.getpayMoneyByOrderApplet({
          isOriginalPrice:this.data.isOriginalPrice,
          courseClassification:courseClassification,
          courseId:this.data.id,
          couponsId:couponsId,
          name:this.data.name,
          remark:this.data.remark,
          organizationId:null,
        }).then(res=>{
          if(res.success){
            wx.hideLoading()
            console.log('支付成功')
            that.setData({
              buyis:true
             })
          }
          // console.log(res)
        })
      }
    
  },
  // 微信使用后台响应的数据调起微信支付
  requestPayment: function (params) {
    let that = this;
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: params.signType,
      paySign: params.paySign,
      success(res) {
        wx.hideLoading()
        console.log(res)
       that.setData({
        buyis:true
       })
      },
      fail(err){
        wx.hideLoading()
        console.log(err)
        that.setData({
          purchase:0
        })
      }
    })
  },
  pay(res) {
    api.orderPayByOrderJsAPIApplet({
      orderNumber: res.data
    }).then(res => {
      if (res.success) {
        this.setData({
          buyis: true
        })
      }
    })
  },
  // 放弃支付
  abandon() {
    this.setData({
      unload: true
    })
    wx.navigateBack({
      delta: 1
    })
  },
  // 继续支付
  gocontinue() {
    this.setData({
      escis: false
    })
  },
  // 购买成功条到入学通知书
  buyou() {
    this.setData({
      unload:true
    })
    wx.redirectTo({
      url: '/curriculum/pages/inform/index?coupon=' + this.data.currName + '&id=' + this.data.id,
    })
  },
  // 优惠券跳转
  coupon() {
    this.setData({
      recommend: false
    })
    console.log(this.data.discountId)
    wx.navigateTo({
      url: '/curriculum/pages/coupon/index?condition=' + this.data.price + '&id=' + this.data.discountId,
    })
  },
  integrals(){
    console.log('微信')
    if (this.data.weixin) {
      this.setData({
        weixin: false,
      })
      // if(this.data.integralis == true){
      //   console.log(this.data.integralis)
      //   this.setData({
      //     integralis:false
      //   })
      // }
    } else {
      this.setData({
        weixin: true
      })
      
    }
  },
  // 使用积分点击事件
  integral() {
    console.log('aaa')
    // this.data.integralis = true
    if (this.data.integralis) {
      this.setData({
        integralis: false
      })
    } else {
      this.setData({
        integralis: true
      })
    }
    this.aaa(this.data.res)
  },
  // 隐藏遮罩层
  hideModal: function () {
    this.setData({
      signUpNowis: false
    })
    console.log(111)
    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  signUpNow() {
    if (this.data.signUpNowis) {
      // this.setData({
      //   signUpNowis:
      // })

      // this.showModal()
    } else {
      this.setData({
        signUpNowis: true
      })

      this.showModal()
    }
  },
  /*显示*/
  showModal: function () {

    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  aaa(res) {
    console.log(res, this.data.type)
    console.log(typeof this.data.type)
    console.log(this.data.price)
    if (this.data.type == 'receive' || this.data.price <= 0) {
      console.log('免费')
      this.setData({
        weixin: false,
        integralis: false,
        coupon: 0,
      })
    } else {
      console.log('付费')
      var _this = this
      if (this.data.coupon >= this.data.price) {
        console.log('优惠券大于实际金额')
        this.setData({
          weixin: false,
          integralis: true,
          paid:0
        })
      } else {
        console.log('优惠券小于实际金额')
        if (!this.data.integralis) {
          console.log('使用积分')
          // 商品价格
          let wprice = _this.data.price ? _this.data.price : 0;
          // 优惠券
          let wcoupon = _this.data.coupon ? _this.data.coupon : 0;
          // 积分剩余
          let wmoney = _this.data.money ? _this.data.money : 0;
          // 积分抵扣
          let wdedu = _this.data.dedu ? _this.data.dedu : 0;
          // 实付
          let wpaid = wprice - wcoupon - wmoney
          if (wmoney <= 0) {
            _this.setData({
              weixin: true,
              wdedu: 0
            })
            console.log('积分等于0')
            this.setData({
              dedu: 0
            })
          } else {
            wdedu = wprice - wcoupon
            console.log('有积分时' + wdedu)
            if (wdedu >= wmoney) {
              console.log('抵扣积分大于积分剩余' + wdedu)
              this.setData({
                weixin: true,
                dedu: wmoney
              })
            } else {
              console.log('抵扣积分小于积分剩余' + wdedu)
              this.setData({
                weixin: false,
                dedu: wdedu
              })
            }
          }
          // 实际支付
          if (wpaid <= 0) {
            this.setData({
              paid: 0
            })
          } else {
            this.setData({
              paid: wpaid
            })
          }
          console.log('商品价格' + wprice)
          console.log('优惠券' + wcoupon)
          console.log('积分剩余' + wmoney)
          console.log('积分抵扣' + wdedu)
          console.log('实付' + wpaid)
        } else {
          console.log('不使用积分')
          console.log('优惠券小于实际金额')
          // 商品价格
          let wprice = _this.data.price ? _this.data.price : 0;
          // 优惠券
          let wcoupon = _this.data.coupon ? _this.data.coupon : 0;
          // 积分剩余
          let wmoney = _this.data.money ? _this.data.money : 0;
          // 积分抵扣
          let wdedu = _this.data.dedu ? _this.data.dedu : 0;
          // 实付
          let wpaid = wprice - wcoupon
          wdedu = 0
          console.log('有积分时' + wdedu)
          if (wdedu >= wmoney) {
            console.log('抵扣积分大于积分剩余' + wdedu)
            this.setData({
              dedu: wmoney
            })
          } else {
            console.log('抵扣积分小于积分剩余' + wdedu)
            this.setData({
              weixin: true,
              dedu: wdedu
            })
          }
          // 实际支付
          if (wpaid <= 0) {
            this.setData({
              paid: 0
            })
          } else {
            this.setData({
              paid: wpaid
            })
          }
          console.log('商品价格' + wprice)
          console.log('优惠券' + wcoupon)
          console.log('积分剩余' + wmoney)
          console.log('积分抵扣' + wdedu)
          console.log('实付' + wpaid)

        }
      }
    }
  },
  // 立即领取
  receive() {
    let couponsId = this.data.discountId ? this.data.discountId : null;
    let isBalance = this.data.integralis ? 'no' : 'yes';
    let name = this.data.name;
    let remark = this.data.remark
    api.orderPayMoneyByOrder({
      courseClassification:this.data.classification, //课程类型
      courseId: this.data.id, //课程id
      couponsId: couponsId, //优惠券id
      payType: "wechat",
      isBalance:isBalance,

      name: name,
      remark:remark,

    }).then(res => {
      this.setData({
        buyis:true
      })
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var isOriginalPrice = options.isOriginalPrice

    console.log(options)
    var orderNo = options.orderNo ? options.orderNo : null; //订单号
    if(orderNo != null){
      var score = options.score ? options.score :0
      var couponMoney = options.couponMoney ? options.couponMoney :0
      var payMoney = options.payMoney // 应付金额
      console.log(score)
      this.setData({
        dingis:false,
        corderNo:orderNo,
        score:score, //学到币
        couponMoney:couponMoney,//优惠券
        payMoney:payMoney
      })
    } else{
      this.setData({
        dingis:true
      })
    }
    if(!this.data.buyis){
      wx.enableAlertBeforeUnload({
        message:'确认要放弃付款吗？',
        success: function (res) {
          console.log("方法注册成功：", res);
        },
        fail: function (errMsg) {
          console.log("方法注册失败：", errMsg);
        },
      })
    }
    var Xd_token = options.token
    console.log(Xd_token)
    if (Xd_token) {
    } else {
      wx.showLoading({
        title: '未登录',
      })
    }
    wx.showLoading({
      title: '加载中',
    })
    var id = options.id
    var Classification = options.classification
    console.log(options)
    var escis = options.escis
    this.setData({
      id: id,
      classification: Classification,
      escis: escis,
      name:options.name,
      remark:options.remark,
      isOriginalPrice:isOriginalPrice
    })
    // 页面数据获取
    console.log(this.data.isOriginalPrice)
    api.buypurchase({
      courseClassification: Classification,
      courseId: Number(id),
      'isOriginalPrice':this.data.isOriginalPrice,
    }).then(res => {
      this.setData({
        discountId: res.data.couponsId,
        coupon: res.data.couponsDetailsMoney,
        res: res.data,
        currName: res.data.currName,
        currimg: res.data.cover,
        money: res.data.money,
        price: res.data.price,
        // price:30000,
        type: res.data.type
      })
      this.aaa(res.data)
      console.log(res)
      if (this.data.discountId == null) {
        console.log('无优惠')
        this.setData({
          discountis: true,
          recommend:false
        })
      } else {
        console.log('优惠')
        this.setData({
          discountis: false,
          recommend:true
        })
      }
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.discountId){
      this.setData({
        discountis:false
      })
    }
    console.log('一、页面显示',this.data.discountId,this.data.coupon,this.data.paid)
    this.aaa(this.data.res)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
    // if (!this.data.unload) {
    //   console.log(this.data.id)
    //   // wx.navigateBack({
    //   //   delta: -1
    //   // })
    //   this.setData({
    //     escis: true
    //   })
    //   wx.navigateTo({
    //     url: '/curriculum/pages/purchase/index?id=' + this.data.id + '&classification=' + this.data.classification + '&escis=' + 'true',
    //   })
    //   console.log('aaa')
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})